package com.gblfy.qywxin.controller;

import com.gblfy.qywxin.service.QywxInnerMiniService;
import com.gblfy.qywxin.utils.JWTUtils;
import com.gblfy.qywxin.vo.JsonData;
import com.gblfy.qywxin.vo.QywxInnerUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/mini")
public class QywxMiniController {
    private static final Logger logger = LoggerFactory.getLogger(QywxMiniController.class);

    @Value("${qywx.mini.corpId}")
    private String corpId;

    @Autowired
    private QywxInnerMiniService qywxInnerMiniService;

    @GetMapping("/login")
    public JsonData login(@RequestParam(value = "code", required = false) String code) {
        logger.info("accept code->{}", code);
        Map result = qywxInnerMiniService.getOauthUser(corpId, code);
        logger.info("accept result->{}", result);

        //本案例仅从企业微信接口获取未从数据表中获取
        QywxInnerUser user = new QywxInnerUser();
        user.setCorpId(corpId);
        user.setUserId((String) result.get("userId"));
        String token = JWTUtils.geneJsonWebToken(user);

        result.put("token", token);
        return JsonData.buildSuccess(result);
    }
}
